package com.yingjia.yingjiauniversity.json.gson;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <重新处理List的反序列化>
 *
 * @author: guoxiangxun
 * @date: 16-7-7 下午9:08
 * @version: v1.0
 */
public class ListDeserializer implements JsonDeserializer<List<Object>> {

    private Gson gson;

    public void setGson(Gson gson) {
        this.gson = gson;
    }

    public List<Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        List<Object> m = new ArrayList<Object>();
        JsonArray arr = json.getAsJsonArray();
        for (JsonElement jsonElement : arr) {
            if (jsonElement.isJsonObject()) {
                m.add(gson.fromJson(jsonElement, Map.class));
            } else if (jsonElement.isJsonArray()) {
                m.add(gson.fromJson(jsonElement, List.class));
            } else if (jsonElement.isJsonPrimitive()) {
                Number num = null;
                try {
                    num = NumberFormat.getInstance().parse(jsonElement.getAsString());
                } catch (Exception e) {
                }
                m.add(num);
            }
        }
        return m;
    }
}
